package com.tsystems.school;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Random;

/**
 * Created by IntelliJ IDEA.
 * User: victorn
 * Date: 8/18/11
 * Time: 5:15 PM
 * To change this template use File | Settings | File Templates.
 */
public class ProducerConsumerTest {

    static LinkedList<Task> tasks = new LinkedList<Task>();

    public class Producer implements Runnable {


        /**
         * When an object implementing interface <code>Runnable</code> is used
         * to create a thread, starting the thread causes the object's
         * <code>run</code> method to be called in that separately executing
         * thread.
         * <p/>
         * The general contract of the method <code>run</code> is that it may
         * take any action whatsoever.
         *
         * @see Thread#run()
         */
        public void run() {
            produce();
        }

        private void produce(){

            Random r = new Random();
            int timeout = r.nextInt();

            while(timeout < 2000){
                timeout = r.nextInt();
            }

            Task task = new Task(timeout);

            synchronized (tasks){
                tasks.addLast(task);
            }
        }
    }


    public class Consumer implements Runnable{

        /**
         * When an object implementing interface <code>Runnable</code> is used
         * to create a thread, starting the thread causes the object's
         * <code>run</code> method to be called in that separately executing
         * thread.
         * <p/>
         * The general contract of the method <code>run</code> is that it may
         * take any action whatsoever.
         *
         * @see Thread#run()
         */
        public void run() {
            consume();
        }

        public void consume(){
            Task task = null;

            synchronized (tasks){
                task = tasks.getLast();
            }

            if(task != null){
                task.doTask();
            }
        }

    }

}
